package com.ybkj.chat.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * Created by Administrator on 2016/1/27.
 */
public class PreImeEditText extends EditText {
    // 在edittext上按返回键时，失去焦点

    Context context;
    ClearFocusImplements clearFocusImplements;

    public PreImeEditText(Context context) {
        super(context);
        this.context = context;
    }

    public PreImeEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    public PreImeEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
    }

    public void initImplements(ClearFocusImplements clearFocusImplements) {
        this.clearFocusImplements = clearFocusImplements;
    }

    @Override
    public boolean dispatchKeyEventPreIme(KeyEvent event) {
        if (context != null) {
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive() && (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_MENU)) {
                //释放焦点
                this.clearFocus();
                if (clearFocusImplements != null) {
                    clearFocusImplements.onClearFocus(this, this.getText().toString());
                }
            }
        }
        return super.dispatchKeyEventPreIme(event);
    }

    public interface ClearFocusImplements {
        void onClearFocus(EditText edt, String text);
    }
}
